<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat page</title>
    <!-- 新 Bootstrap4 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <!-- 引入jquery文件 -->
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <!--   fontawesome -->
    <script src="https://kit.fontawesome.com/a66cf41318.js" crossorigin="anonymous"></script>

    <script src="https://cdn.bootcss.com/popper.js/1.12.5/umd/popper.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
Chat Page
<div class="from-group">
    <div>
        <span>当前用户:</span><span id="username" th:text="${username}"></span>
    </div>
    <div class="row">
        <label class="mdui-textfield-label"><i class="fas fa-sms"></i>
            发送内容
        </label><br/>
        <textarea id="msg"></textarea>
    </div>
    <div class="row" style="">
        <button class="mdui-btn mdui-color-theme-accent mdui-ripple"
                onclick="sendMsgToServer()">发送 (enter)
        </button>
        <button class="mdui-btn mdui-color-theme mdui-ripple"
                onclick="clearMsg()">清屏
        </button>
    </div>
</div>

<div>
    <div class="mdui-chip">
                    <span class="mdui-chip-icon mdui-color-blue">
        <span class="mdui-chip-title">聊天内容</span>
    </div>

    <div class="mdui-chip">
        <span class="mdui-chip-title">在线人数</span>
        <span id="chat_num">0</span>
    </div>
    <div class="message_container" style="width: 500px; border: azure 1px solid;">

    </div>
</div>

<script>

    /**
     * WebSocket客户端
     *
     */
    function createWebSocket() {
        /**
         * WebSocket客户端
         */
        var serviceUri = 'ws://localhost:8080/chat';
        var webSocket = new WebSocket(serviceUri);
        /**
         * 打开连接的时候
         */
        webSocket.onopen = function (event) {
            console.log('websocket打开连接....');
        };

        /**
         * 接受服务端消息
         */
        webSocket.onmessage = function (event) {
            console.log('websocket：%c' + event.data);
            // 获取服务端消息
            var message = JSON.parse(event.data) || {};

            var $messageContainer = $('.message_container');
            if (message.type === 'TALK') {
                var insertOneHtml = '<div class="mdui-card" style="margin: 10px 0;">' +
                    '<div class="some-class">' +
                    '<div class="message_content">' + message.username + "：" + message.message + '</div>' +
                    '</div></div>';
                $messageContainer.append(insertOneHtml);
            }
            // 更新在线人数
            $('#chat_num').text(message.onlineCount);
            //防止刷屏
            var $cards = $messageContainer.children('.mdui-card:visible').toArray();
            if ($cards.length > 5) {
                $cards.forEach(function (item, index) {
                    index < $cards.length - 5 && $(item).slideUp('fast');
                });
            }
        };

        /**
         * 关闭连接
         */
        webSocket.onclose = function (event) {
            console.log('WebSocket关闭连接');
        };

        /**
         * 通信失败
         */
        webSocket.onerror = function (event) {
            console.log('WebSocket发生异常');

        };
        return webSocket;
    }

    var webSocket = createWebSocket();


    /**
     * 通过WebSocket对象发送消息给服务端
     */
    function sendMsgToServer() {
        var $message = $('#msg');
        if ($message.val()) {
            webSocket.send(JSON.stringify({username: $('#username').text(), msg: $message.val()}));
            $message.val(null);
        }

    }

    /**
     * 清屏
     */
    function clearMsg() {
        $(".message_container").empty();
    }

    /**
     * 使用ENTER发送消息
     */
    document.onkeydown = function (event) {
        var e = event || window.event || arguments.callee.caller.arguments[0];
        e.keyCode === 13 && sendMsgToServer();
    };


</script>

</body>
</html>